﻿using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web.UI;
using Cms.Utilities;
using Cms.Web.Framework;
using Cms.Web.Framework.Infrastructure;
using iLib.Web.UI;

namespace Cms.Web.UI
{
    public partial class Thumbnail : Page
    {
        protected override void OnLoad(EventArgs e)
        {
            base.OnLoad(e);
            try
            {
                GenerateThumbnail();
            }
            catch (Exception ex)
            {
                Logging.LogError("Thumbnail creation failed. ", ex);
                throw;
            }
            Response.End();
        }

        public void GenerateThumbnail()
        {

            Image thumbnailImage = ResizeImage();
            var memoryStream = new MemoryStream();
            thumbnailImage.Save(memoryStream, ImageFormat.Png);
            thumbnailImage.Dispose();
            Response.ClearContent();
            Response.ClearHeaders();
            Response.ContentType = "image/png";
            memoryStream.WriteTo(Response.OutputStream);
            memoryStream.Close();
            memoryStream.Dispose();
        }

        public Image ResizeImage()
        {
            string imagePath = Server.MapPath(Url.VirtualPath + Request.QueryString["file"]);
            Image thumbnail = null;
            using (Image photo = new Bitmap(imagePath))
            {
                Size thumbnailSize = new Size(
                    int.Parse(Request.QueryString["width"]),
                    int.Parse(Request.QueryString["height"]));
                thumbnail = ImageResizer.Resize(photo, thumbnailSize);
                photo.Dispose();
            }
            return thumbnail;
        }
    }
}